//
//  OIScanViewController.m
//  EducationOID
//
//  Created by slz on 2017/5/10.
//  Copyright © 2017年 bnsr. All rights reserved.
//

#import "OIScanViewController.h"
#import "OIScanPermissions.h"
#import "OIQRScanResultViewController.h"
#import "NSString+OIDAnalysis.h"
#import "OIDInfoRequestModel.h"
#import "NSURL+QueryDict.h"
#import "NewWebViewController.h"
#import "OIDCacheManager.h"
#import "OIDSystemSettingManager.h"
#import "BaseHttpTool.h"


@interface OIScanViewController ()<MFWDataObserver,UINavigationControllerDelegate,UIImagePickerControllerDelegate>

@end

@implementation OIScanViewController
{
    OIDInfoRequestModel * _oidModel;
    NSString * _scanString;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"扫描二维码";

    UIBarButtonItem * item = [UIBarButtonItem itemWithImage:@"top_back_1" selectImage:nil addTarget:self andAction:@selector(backAction)];
    self.navigationItem.leftBarButtonItem = item;
    UIBarButtonItem * rightItem = [UIBarButtonItem itemWIthTitle:@"相册" addTarget:self andAction:@selector(moreScanAction)];
    self.navigationItem.rightBarButtonItem = rightItem;
    // Do any additional setup after loading the view.
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    UIColor *color=[UIColor blackColor];
    UIImage *image=[UIImage imageWithColor:color];
    [self.navigationController.navigationBar setBackgroundImage:image
                                                 forBarPosition:UIBarPositionTopAttached
                                                     barMetrics:UIBarMetricsDefault];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self drawScanView];
    [self performSelector:@selector(startScan) withObject:nil afterDelay:0.2];
}

- (void)drawScanView
{
    if (!self.qRScanView)
    {
        CGRect rect = self.view.frame;
        rect.origin = CGPointMake(0, 0);
        
        self.qRScanView = [[LBXScanView alloc]initWithFrame:rect style:self.style];
        
        [self.view addSubview:self.qRScanView];
    }
    [self.qRScanView startDeviceReadyingWithText:@"相机启动中"];
}


-(void)startScan{
    if ( ![OIScanPermissions cameraPemission] )
    {
        [self.qRScanView stopDeviceReadying];
        
        [self showError:@"  请到设置隐私中开启本程序相机权限   "];
        return;
    }
    
    UIView *videoView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame))];
    videoView.backgroundColor = [UIColor clearColor];
    [self.view insertSubview:videoView atIndex:0];
    @weakify(self);
    
    if (!self.scanObj) {
        
        CGRect cropRect = [LBXScanView getScanRectWithPreView:videoView style:self.style];
        
        self.scanObj = [[LBXScanNative alloc]initWithPreView:videoView ObjectType:nil cropRect:cropRect success:^(NSArray<LBXScanResult *> *array) {
            if ([OIDSystemSettingManager  shareManager].tipShake){
                AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
            }
            [weak_self scanResultWithArray:array];
        }];
    
    }
    [self.scanObj startScan];

    [self.qRScanView stopDeviceReadying];
    [self.qRScanView startScanAnimation];
    self.view.backgroundColor = [UIColor clearColor];
}

-(void)showError:(NSString *)str{
    NSLog(@"%@",str);
}

- (void)scanResultWithArray:(NSArray<LBXScanResult*>*)array
{
    if (array && array.count > 0){
        LBXScanResult * result = array[0];
        NSString * scanString = result.strScanned;
        if ([MFWStringUtils isEmptyString:scanString]){
            [self.view showTip:@"二维码扫描失败" completion:^{
                [self.navigationController popViewControllerAnimated:YES];
            }];
            return;
        }
        [self.qRScanView startDeviceReadyingWithText:@"数据请求中..."];
        _scanString = scanString;
        BOOL isUrl = [scanString isUrl];
        
        [[OIDCacheManager shareInstance] uopdateWithAnalysisOidString:_scanString];
        
        OIDCacheManager * manager = [OIDCacheManager shareInstance];
        [manager uopdateWithAnalysisOidString:scanString];
        
        if (isUrl){
            if ([_scanString isContainOidCenter])
            {
                NSURL * url = [NSURL URLWithString:scanString];
                NSString * oidString = [url queryValueWithKey:@"oid"];
                [self requestWithOidString:oidString];
            }else
            {
                [self requestWithOidType1:scanString];
            }
        }else{
            if ([scanString isContainOID])
            {
                scanString = [scanString substringFromIndex:4];
                [self requestWithOidType2:scanString];
            }else
            {
                [self requestWithOidString:scanString];
            }
            //todo 不是url 直接请求
        }
//        OIQRScanResultViewController * resultController = [[OIQRScanResultViewController alloc]init];
//        resultController.resultString = result.strScanned;
//        resultController.isQrcode = YES;
//        [self.navigationController pushViewController:resultController animated:YES];
    }
}

- (void)requestWithOidType2:(NSString *)oidString
{
    [BaseHttpTool get:kAPI_OID_SEARCH_OID_NEW params:@{@"type":@"2",@"url":oidString} success:^(id responseObj) {
        MFWJson * json = [MFWJson jsonWithObject:responseObj];
        BOOL isOID = [json booleanValueForKey:@"parameter"];
        if (!isOID){
            [self.view showTip:@"无效的二维码" completion:^{
                [self.navigationController popViewControllerAnimated:YES];
            }];
        }else
        {
            MFWJson * subJson = [json jsonForKey:@"rows"];
            NSString * successsString = [subJson stringValueForKey:@"url"];
            OIQRScanResultViewController * resultController = [[OIQRScanResultViewController alloc]init];
            resultController.resultSuccessUrl = successsString;
            resultController.isQrcode = NO;
            resultController.isOidValid = YES;
            resultController.canJump = NO;
            [self.navigationController pushViewController:resultController animated:YES];
        }
        
    } failure:^(NSError *error) {
        [self.view showTip:error.localizedDescription];
    }];
}

- (void)requestWithOidType1:(NSString *)oidString
{
    NSString * scanString = oidString;
    NSURL * url = [NSURL URLWithString:oidString];
    if (![url.host isEqualToString:@"weixin.qq.com"]){
        oidString = [NSString stringWithFormat:@"%@://%@",url.scheme,url.host];
        NSLog(@"%@",oidString);
    }
    [BaseHttpTool get:kAPI_OID_SEARCH_OID_NEW params:@{@"type":@"1",@"url":oidString} success:^(id responseObj) {
        [self.qRScanView stopDeviceReadying];

            MFWJson * json = [MFWJson jsonWithObject:responseObj];
            BOOL isOID = [json booleanValueForKey:@"parameter"];
            MFWJson * subJson = [json jsonForKey:@"rows"];
//            NSString * successsString = [subJson stringValueForKey:@"url"];
            OIQRScanResultViewController * resultController = [[OIQRScanResultViewController alloc]init];
            resultController.resultSuccessUrl = scanString;
            resultController.isQrcode = NO;
            resultController.isOidValid = isOID;
            resultController.canJump = YES;
            NSInteger oidType = [subJson intValueForKey:@"oid_type"];
            resultController.canJump = oidType == 2 ? NO :YES;
            resultController.resultName = [subJson stringValueForKey:@"name"];
            resultController.typeCount = [subJson intValueForKey:@"oid_type"];
            [self.navigationController pushViewController:resultController animated:YES];
    } failure:^(NSError *error) {
        [self.view showTip:error.localizedDescription];
    }];
}


- (void)jumpWebControllerWithUrl:(NSString *)url
{
    NewWebViewController * webController = [[NewWebViewController alloc]init];
    webController.url = url;
    [self.navigationController pushViewController:webController animated:YES];
}

- (void)requestWithOidString:(NSString *)oidString{
    if(_oidModel == nil) {
        _oidModel = [OIDInfoRequestModel managedModelInstance];
        [[_oidModel class] addDataObserver:self];
    }
    [_oidModel requestRefresh:[_oidModel actionDataWithOIDString:oidString]];
}

-(void)requestFinishedForTask:(MFWTask *)task withModel:(MFWDataModel *)model dataId:(NSString *)dataId requestType:(MFWDataRequestType)type itemArray:(NSArray *)itemArray success:(BOOL)bSuccess error:(NSError *)error{
    [self.qRScanView stopDeviceReadying];
    if (model == _oidModel){
        if (bSuccess && error == nil){
            MFWJson * json = [model jsonDataForDataId:dataId];
            BOOL isOid = [json booleanValueForKey:@"parameter"];
            if (!isOid){
                    NSString * urlString = _scanString;
                    BOOL isUrl = [urlString isUrl];
                    if (isUrl){
                        [self jumpWebControllerWithUrl:urlString];
                    }else{
                        NSString * errorInfo = [json stringValueForKey:@"data"];
                        [self.view showTip:errorInfo completion:^{
                            [self.navigationController popViewControllerAnimated:YES];
                        }];
                    }
            }else{
                NSString * successsString = [json stringValueForKey:@"data"];
                OIQRScanResultViewController * resultController = [[OIQRScanResultViewController alloc]init];
                resultController.resultSuccessUrl = successsString;
                resultController.isQrcode = NO;
                resultController.canJump = YES;
                resultController.isOidValid = YES;
                [self.navigationController pushViewController:resultController animated:YES];
            }
        }else{
            [self.view showTip:@"请求错误~" completion:^{
                [self.navigationController popViewControllerAnimated:YES];
            }];
        }
    }

}

- (void)moreScanAction{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    
    picker.delegate = self;
    
    //部分机型有问题
    //    picker.allowsEditing = YES;
    
    
    [self presentViewController:picker animated:YES completion:nil];
}

-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    __block UIImage* image = [info objectForKey:UIImagePickerControllerEditedImage];
    
    if (!image){
        image = [info objectForKey:UIImagePickerControllerOriginalImage];
    }
    
    @weakify(self);
    
    [ZXingWrapper recognizeImage:image block:^(ZXBarcodeFormat barcodeFormat, NSString *str) {
        
        LBXScanResult *result = [[LBXScanResult alloc]init];
        result.strScanned = str;
        result.imgScanned = image;
        result.strBarCodeType = [self convertZXBarcodeFormat:barcodeFormat];
        
        [weak_self scanResultWithArray:@[result]];
    }];
}

- (NSString*)convertZXBarcodeFormat:(ZXBarcodeFormat)barCodeFormat
{
    NSString *strAVMetadataObjectType = nil;
    
    switch (barCodeFormat) {
        case kBarcodeFormatQRCode:
            strAVMetadataObjectType = AVMetadataObjectTypeQRCode;
            break;
        case kBarcodeFormatEan13:
            strAVMetadataObjectType = AVMetadataObjectTypeEAN13Code;
            break;
        case kBarcodeFormatEan8:
            strAVMetadataObjectType = AVMetadataObjectTypeEAN8Code;
            break;
        case kBarcodeFormatPDF417:
            strAVMetadataObjectType = AVMetadataObjectTypePDF417Code;
            break;
        case kBarcodeFormatAztec:
            strAVMetadataObjectType = AVMetadataObjectTypeAztecCode;
            break;
        case kBarcodeFormatCode39:
            strAVMetadataObjectType = AVMetadataObjectTypeCode39Code;
            break;
        case kBarcodeFormatCode93:
            strAVMetadataObjectType = AVMetadataObjectTypeCode93Code;
            break;
        case kBarcodeFormatCode128:
            strAVMetadataObjectType = AVMetadataObjectTypeCode128Code;
            break;
        case kBarcodeFormatDataMatrix:
            strAVMetadataObjectType = AVMetadataObjectTypeDataMatrixCode;
            break;
        case kBarcodeFormatITF:
            strAVMetadataObjectType = AVMetadataObjectTypeITF14Code;
            break;
        case kBarcodeFormatRSS14:
            break;
        case kBarcodeFormatRSSExpanded:
            break;
        case kBarcodeFormatUPCA:
            break;
        case kBarcodeFormatUPCE:
            strAVMetadataObjectType = AVMetadataObjectTypeUPCECode;
            break;
        default:
            break;
    }
    
    
    return strAVMetadataObjectType;
}

- (void)backAction{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
